package cn.thomas.clock.controller;

import cn.thomas.clock.config.RabbitMQConfig;
import cn.thomas.clock.domain.dto.ClockInDTO;
import cn.thomas.clock.domain.dto.ClockInInfoDTO;
import cn.thomas.clock.domain.vo.ResponseVO;
import cn.thomas.clock.enums.ErrorEnum;
import cn.thomas.clock.service.ClockInService;
import cn.thomas.clock.utils.IpUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Tomas
 * @version 1.0.0
 * @date 2021-10-18 09:22
 **/
@Api(value = "XN 外网打卡", tags = {"打卡接口"})
@RestController
@RequestMapping("/clockIn")
public class ClockController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ClockInService clockInService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("打工的一天从打卡开始~")
    @PostMapping("/clockIn")
    public ResponseVO<?> clockIn(@RequestBody ClockInDTO clockIn) {
        ClockInInfoDTO entity = new ClockInInfoDTO();
        try {
            //mq发送
            rabbitTemplate.convertAndSend(RabbitMQConfig.XINNUO_CLOCK__TOPIC_EXCHANGE, "", JSONObject.toJSONString(clockIn));
            entity.setClockInUser(clockIn.getUsername());
            entity.setCreateTime(new Date());
            entity.setClockInIp(IpUtils.getRemoteHost(request));
            entity.setMsg("推送打卡成功");
        } catch (AmqpException e) {
            entity.setMsg(e.getMessage());
            e.printStackTrace();
        } finally {
            entity.setId(IdWorker.getId());
            clockInService.save(entity);
        }
        return ResponseVO.result(ErrorEnum.SUCCESS, entity.getMsg());
    }


    @ApiOperation("打卡是否成功验证 （打卡后10分钟内可验证）")
    @GetMapping("/verifySignIn/{username}")
    public ResponseVO<?> verifySignIn(@PathVariable String username) {
        String body = redisTemplate.opsForValue().get("XINNUO:CLOCKIN:USERNAME:sb:" + username);
        System.out.println(body);
        return ResponseVO.result(ErrorEnum.SUCCESS, body);
    }

    @ApiOperation("打卡回调")
    @PostMapping("/clockCallbock")
    public ResponseVO<?> clockCallback() {
        return null;
    }

}
